<?php

class GenealogyController extends Controller
{

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete', 'tree', 'imageUpload', 'saveEntity'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

    public function actionTree($id=null)
    {
        $catModel = Cat::model()->findByPk($id);
        if ($catModel === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }

        $collection = new CAttributeCollection();
        $genealogyEntityModels = GenealogyEntity::model()->findAll('cat_id = :cat_id',
            array(':cat_id'=>Yii::app()->getRequest()->getParam('id', false)));

        $genealogyEntities = array();
        foreach($genealogyEntityModels as $model){
            $genealogyEntities[$model->code] = $model;
        }

        $collection->father = $this->_getGenealogyEntity($genealogyEntities, 'father');

        $collection->fatherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherFather');
        $collection->fatherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherMother');

        $collection->fatherFatherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherFatherFather');
        $collection->fatherFatherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherFatherMother');
        $collection->fatherMotherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherMotherFather');
        $collection->fatherMotherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherMotherMother');

        $collection->fatherFatherFatherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherFatherFatherFather');
        $collection->fatherFatherFatherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherFatherFatherMother');
        $collection->fatherFatherMotherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherFatherMotherFather');
        $collection->fatherFatherMotherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherFatherMotherMother');
        $collection->fatherMotherFatherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherMotherFatherFather');
        $collection->fatherMotherFatherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherMotherFatherMother');
        $collection->fatherMotherMotherFather = $this->_getGenealogyEntity($genealogyEntities, 'fatherMotherMotherFather');
        $collection->fatherMotherMotherMother = $this->_getGenealogyEntity($genealogyEntities, 'fatherMotherMotherMother');


        $collection->mother = $this->_getGenealogyEntity($genealogyEntities, 'mother');
        $collection->motherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherFather');
        $collection->motherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherMother');

        $collection->motherFatherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherFatherFather');
        $collection->motherFatherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherFatherMother');
        $collection->motherMotherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherMotherFather');
        $collection->motherMotherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherMotherMother');

        $collection->motherFatherFatherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherFatherFatherFather');
        $collection->motherFatherFatherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherFatherFatherMother');
        $collection->motherFatherMotherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherFatherMotherFather');
        $collection->motherFatherMotherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherFatherMotherMother');
        $collection->motherMotherFatherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherMotherFatherFather');
        $collection->motherMotherFatherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherMotherFatherMother');
        $collection->motherMotherMotherFather = $this->_getGenealogyEntity($genealogyEntities, 'motherMotherMotherFather');
        $collection->motherMotherMotherMother = $this->_getGenealogyEntity($genealogyEntities, 'motherMotherMotherMother');

        $this->render('tree',array(
            'cat'=>$catModel,
            'collection'=>$collection,
        ));
    }

    public function actionSaveEntity()
    {
        if ($catId = Yii::app()->getRequest()->getPost('cat_id', false) &&
            $code = Yii::app()->getRequest()->getPost('code', false)) {
            $entity = GenealogyEntity::model()->findByPk(array('cat_id'=>$catId, 'code'=>$code));
            if (!$entity) {
                $entity = new GenealogyEntity;
            }
            $entity->setAttributes($_POST);
            if ($entity->validate()) {
                $entity->save();
            }
        } else {
            throw new CHttpException(500, 'Error while save wtf');
        }

    }

    public function actionImageUpload() {
        $uploadDir = 'images/genealogy';
        // HTTP headers for no cache etc
        header('Content-type: text/plain; charset=UTF-8');
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        // Settings
        $targetDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "genealogy";
        $maxFileAge = 60 * 60; // Temp file age in seconds

        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Get parameters
        $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
        $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

        // Clean the fileName for security reasons
        $fileName = preg_replace('/[^\w\._\s]+/', '', $fileName);

        // Create target dir
        if (!file_exists($targetDir))
            @mkdir($targetDir);

        // Remove old temp files
        if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
            while (($file = readdir($dir)) !== false) {
                $filePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // Remove temp files if they are older than the max age
                if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
                    @unlink($filePath);
            }

            closedir($dir);
        } else
            throw new CHttpException (500, Yii::t('app', "Can't open temporary directory."));


        // Look for the content type header
        if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];

        if (isset($_SERVER["CONTENT_TYPE"]))
            $contentType = $_SERVER["CONTENT_TYPE"];


        if (strpos($contentType, "multipart") !== false) {


            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = fopen($_FILES['file']['tmp_name'], "rb");
                    if ($in) {
                        while ($buff = fread($in, 4096))
                            fwrite($out, $buff);
                    } else
                        throw new CHttpException (500, Yii::t('app', "Can't open input stream."));
                    fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                } else
                    throw new CHttpException (500, Yii::t('app', "Can't open output stream."));
            } else
                throw new CHttpException (500, Yii::t('app', "Can't move uploaded file."));
        } else {
            // Open temp file
            $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = fopen("php://input", "rb");
                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                } else
                    throw new CHttpException (500, Yii::t('app', "Can't open input stream."));

                fclose($out);
            } else
                throw new CHttpException (500, Yii::t('app', "Can't open output stream."));
        }


        //process the file
        $file_id = substr($fileName, 0, strripos($fileName, '.'));
        $filename = $_FILES['file']['name'];
        $file_basename = substr($filename, 0, strripos($filename, '.'));
        $file_ext = substr($filename, strripos($filename, '.'));
        $file_size = $_FILES['file']['size'];
        $file_type = $_FILES['file']['type'];
        $file_error = $_FILES['file']['error'];
        $app_root = substr(Yii::app()->baseUrl, 1, strlen(Yii::app()->baseUrl) - 1);
        $app_root = $app_root ? $app_root . DIRECTORY_SEPARATOR : '';

        $upload_path = DIRECTORY_SEPARATOR . $app_root . $uploadDir;

        //Return Array
        $ret = array('result' => '1',
            'file_error' => $file_error,
            'filename' => str_replace(' ', '', $filename),
            'file_id' => $file_id,
            'file_basename' => str_replace(' ', '', $file_basename),
            'file_ext' => $file_ext,
            'file_size' => $file_size,
            'file_type' => $file_type,
            'upload_path' => $upload_path,
        );

        if (intval($chunk) + 1 >= intval($chunks)) {
            $originalname = $fileName;
            if (isset($_SERVER['HTTP_CONTENT_DISPOSITION'])) {
                $arr = array();
                preg_match('@^attachment; filename="([^"]+)"@', $_SERVER['HTTP_CONTENT_DISPOSITION'], $arr);
                if (isset($arr[1]))
                    $originalname = $arr[1];
            }

            // **********************************************************************************************
            // Do whatever you need with the uploaded file, which has $originalname as the original file name
            // and is located at $targetDir . DIRECTORY_SEPARATOR . $fileName
            // **********************************************************************************************

            $temppath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

            $app_root = substr(Yii::app()->baseUrl, 1, strlen(Yii::app()->baseUrl) - 1);
            $app_root = $app_root ? $app_root . DIRECTORY_SEPARATOR : '';

            $dest = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR .
                $app_root .
                //      'assets'.     DIRECTORY_SEPARATOR .
                $uploadDir . DIRECTORY_SEPARATOR .
                $file_id . $file_ext;
            //  var_dump($dest);


            //copy from temporary to final directory
            @copy($temppath, $dest);
        }

        // Return response
        echo (json_encode($ret));
        return;
    }

    private function _getGenealogyEntity ($entities, $name) {
        if (!empty($entities[$name])) {
            return $entities[$name];
        } else {
            $entity = new GenealogyEntity;
            $entity->name = $name;
            return $entity;
        }
    }
}
